package easy;

/**
 * Created by daodao on 2017/11/30.
 * problem 7
 * description: Given a 32-bit signed integer, reverse digits of an integer.
 * Example 1:
 *  Input: 123
 *  Output: 321
 * Example 2:
 *  Input: -123
 *  Output: -321
 * Example 3:
 *  Input: 120
 *  Output: 21
 * Note: Assume we are dealing with an environment which could only hold integers within the 32-bit signed integer range.
 * For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
 */
public class ReverseInteger {
    public static int reverse(int x) {
        int result = 0;
        int digit;
        if (x > Integer.MAX_VALUE || x <= Integer.MIN_VALUE) {
            return result;
        }
        boolean isPositive = x >= 0;
        int y = isPositive ? x : -x;
        int multmin = Integer.MAX_VALUE / 10;
        while (y / 10 >= 0 && y != 0) {
            digit = y % 10;
            if (result > multmin) {
                return 0;
            } else if (result == multmin){
                if (digit > 7) {
                    return 0;
                }
            }
            result *= 10;
            result += digit;
            y = y / 10;
        }
        return isPositive ? result : -result;
    }
}
